const mongoose = require('mongoose')
const md5 = require('md5')
const UserModel = require('./models/UserModel')

module.exports = function () {
  // 连接数据库, 返回promise
  const promise = mongoose.connect('mongodb://localhost:27017/user_manage')

  // 绑定连接成功的监听
  mongoose.connection.on('open', async () => {
    console.log('数据库连接成功')
    // 如果users中没有admin, 插入admin用户
    const user = await UserModel.findOne({username: 'admin'})
    if (!user) {
      UserModel.create({
        username: 'admin',
        pwd: md5('111111'),
        profile: '/upload/admin.png'
      })
    }
  })

  // 绑定连接失败的监听
  mongoose.connection.on('error', () => {
    console.log('数据库连接失败')
  })

  // 返回连接的promise => 用于在app中连接成功后启动服务
  return promise
}

